package com.how2java.tmall.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.how2java.tmall.mapper.OrderMapper;
import com.how2java.tmall.pojo.Order;
import com.how2java.tmall.pojo.Orderitem;
import com.how2java.tmall.pojo.User;
import com.how2java.tmall.service.OrderItemService;
import com.how2java.tmall.service.OrderService;
import com.how2java.tmall.service.UserService;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private OrderItemService orderItemService;
	
	@Override
	public void add(Order c) {
		orderMapper.insertSelective(c);
	}

	@Override
	public void delete(int id) {
		orderMapper.deleteByPrimaryKey(id);
	}

	@Override
	public void update(Order c) {
		orderMapper.updateByPrimaryKeySelective(c);
	}

	@Override
	public Order get(int id) {
		return orderMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Order> list() {
		
		List<Order> oList = orderMapper.getList();
		
		setUser(oList);
		
		return oList;
	}
	
	public void setUser(List<Order> os){
        for (Order o : os)
            setUser(o);
    }
    public void setUser(Order o){
        int uid = o.getUid();
        User u = userService.get(uid);
        o.setUser(u);
    }

	@SuppressWarnings("unused")
	@Override
	@Transactional(propagation= Propagation.REQUIRED,rollbackForClassName="Exception")
	public float add(Order o, List<Orderitem> ois) {
		float total = 0;
        add(o);
 
        if(false)
            throw new RuntimeException();
 
        for (Orderitem oi: ois) {
            oi.setOid(o.getId());
            orderItemService.update(oi);
            total+=oi.getProduct().getPromoteprice()*oi.getNumber();
        }
        return total;
	}

	
	
	@Override
	public List<Order> listByUidAndNotDelete(int uid) {
		
		
		
		return orderMapper.getListByUidAndNotDelete(uid);
	}
	
	
	

}
